package javaAdvanced;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author cuiH
 * Date: 13-10-24
 */
public class ThreadScopeShareData {
    /*
    * 一直测试线程在一定范围之内：线程内共享数据，线程间数据独立
    * */
    private static int data = 0;              //设置一块静态的数据领域
    private static Map<Thread,Integer> threadData = new HashMap();
    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {                            //此时构造两个线程，这样就造成同一个数据域被不同线程调用时候，数据不同了
            new Thread(
                    new Runnable() {
                        @Override
                        public void run() {
                            data = new Random().nextInt();
                            System.out.println(Thread.currentThread().getName() + " put data:" + data);
                            threadData.put(Thread.currentThread(),data);
                            new A().get();
                            new B().get();
                        }
                    }
            ).start();
        }
    }

    static class A {
        public void get() {
            int data = threadData.get(Thread.currentThread());
            System.out.println("A from " + Thread.currentThread().getName() + " get data:" + data);
        }
    }

    static class B {
        public void get() {
            int data = threadData.get(Thread.currentThread());
            System.out.println("B from " + Thread.currentThread().getName() + " get data:" + data);
        }
    }
}
/*
* 实验结果
* 单线程正常：
* Thread-0 has put data:-501008558
Thread-0 has data:-501008558
Thread-0 has data:-501008558

双线程不加以控制
后一个put的数据对前一个进行了覆盖，但是前一个数据正在使用
Thread-0 put data:-337359748
Thread-1 put data:817254732
A from Thread-0 get data:817254732
A from Thread-1 get data:817254732
B from Thread-0 get data:817254732
B from Thread-1 get data:817254732

加上put之后的方式
Thread-0 put data:68372030
A from Thread-0 get data:68372030
B from Thread-0 get data:68372030
Thread-1 put data:1133553140
A from Thread-1 get data:1133553140
B from Thread-1 get data:1133553140
*/
